/******************************************************************************************************
Copyright (C) 2010 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

function EventHandler()
{
	this.diag=new Dialog()
	this.diag.title = "My Dialog"
	this.callNumber=0
}

EventHandler.prototype.onMouseButtonDblClick = function(aJSONString)
{
	var aArgument = JSON.parse(aJSONString)
	var actDoc = mainWindow.activeDocument
	if(aArgument.itemId!=undefined) {
		var item = actDoc.getItem(aArgument.itemId);
		if(item!=undefined) {
			if(item.name=="NMR Spectrum" && aArgument.button=="LeftButton") {
				var nmrItem = new NMRSpectrum(item);
				this.diag.title=this.callNumber+" "+nmrItem.toString()
				this.callNumber++
				return true;
			}
		}
	}
	return false;
}

EventHandler.prototype.onKeyPress = function(aJSONString)
{
	var aArgument = JSON.parse(aJSONString)
	var actDoc = mainWindow.activeDocument
	if(aArgument.itemId!=undefined) {
		var item = actDoc.getItem(aArgument.itemId);
		if(item!=undefined) {
			if(item.name=="NMR Spectrum" && aArgument.key!="Esc") {
				var nmrItem = new NMRSpectrum(item);
				MessageBox.information(this.callNumber+" "+nmrItem.toString()+"\nKey: "+aArgument.key, MessageBox.Ok)
				this.callNumber++
				return true;
			}
		}
	}
	return false;
}

/** Function that creates a dialog that handles events from the GUI
*/
function dialogEvent()
{
	Application.eventHandler = new EventHandler()
	Application.eventHandler.diag.show();
		
	Application.mainWindow.installEventHandler("MouseButtonDblClick", "Application.eventHandler.onMouseButtonDblClick")
	Application.mainWindow.installEventHandler("KeyPress", "Application.eventHandler.onKeyPress")
	
	while(Application.eventHandler.diag.visible) {
		mainWindow.sleep(1);
		mainWindow.processEvents();
	}
	Application.mainWindow.removeEventHandler("MouseButtonDblClick", "Application.eventHandler.onMouseButtonDblClick")
	Application.mainWindow.removeEventHandler("KeyPress", "Application.eventHandler.onKeyPress")
	Application.eventHandler=undefined
}
